using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using Common;

namespace Controls
{
    public class ColorEdit : System.Windows.Controls.UserControl
    {
        public static readonly DependencyProperty IsReadOnlyProperty;

        public static readonly DependencyProperty ColorProperty;

        public bool IsReadOnly
        {
            get
            {
                return (bool)GetValue(IsReadOnlyProperty);
            }
            set
            {
                SetValue(IsReadOnlyProperty, value);
            }
        }

        public Color Color
        {
            get
            {
                return (Color)GetValue(ColorProperty);
            }
            set
            {
                SetValue(ColorProperty, value);
            }
        }

        static ColorEdit()
        {
            IsReadOnlyProperty = DependencyProperty.Register("IsReadOnly", typeof(bool), typeof(ColorEdit), new UIPropertyMetadata(false));
            ColorProperty = DependencyProperty.Register("Color", typeof(Color), typeof(ColorEdit), new UIPropertyMetadata(Colors.Black));
            FrameworkElement.DefaultStyleKeyProperty.OverrideMetadata(typeof(ColorEdit), new FrameworkPropertyMetadata(typeof(ColorEdit)));
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            UIElement uIElement = GetTemplateChild("PART_Color") as UIElement;
            if (uIElement != null)
            {
                uIElement.MouseLeftButtonDown += eleColor_MouseLeftButtonDown;
            }
        }

        private void eleColor_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (!IsReadOnly && base.IsEnabled)
            {
                ColorWindow colorWindow = new ColorWindow();
                colorWindow.Color = Color;
                if (colorWindow.ShowDialog() == DialogResult.OK)
                {
                    Color = colorWindow.Color;
                }
                e.Handled = true;
            }
        }
    }
}
